#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <memory.h>
#include <termios.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/select.h>

#define BUFFER_SIZE 1024

main()
{
    int gps_fd, nfd, nbytes, i;
    struct timeval tv;
    struct termios tios, orig_tios;
    fd_set read_fd;
    unsigned char buffer[BUFFER_SIZE];

    if((gps_fd = open("/dev/ttyUSB0", O_RDWR)) < 0)
    {
	perror("could not open GPS device over USB");
	return -1;
    }

    memset(&orig_tios, 0, sizeof(struct termios));
    tcgetattr(gps_fd, &orig_tios);
    

    memset(&tios, 0, sizeof(struct termios));
    tios.c_cflag = B57600 | CRTSCTS | CS8 | CLOCAL | CREAD;
    tios.c_iflag = IGNPAR | ICRNL;
    tios.c_oflag = 0;
    tios.c_lflag = ICANON;
    tcflush(gps_fd, TCIFLUSH);
    tcsetattr(gps_fd,TCSANOW,&tios);

    while(1)
    {
	for(;;)
        {
	    FD_ZERO(&read_fd);
    	    FD_SET(gps_fd, &read_fd);
            memset(&tv, 0, sizeof(struct timeval));
	    tv.tv_sec = 1;
    	    tv.tv_usec = 0;
	    errno = 0;
	    nfd = select(gps_fd + 1, &read_fd, NULL, NULL, &tv);
	    if(errno == EINTR) continue;
	    break;
	}
	if(nfd < 0)	
	{
	    perror("select() error");
	    shutdown(gps_fd, 2);
	    return -1;
	}
	if(nfd == 0) 
	{
	    usleep(10);
	    printf(".");
	    continue;
	}
	
	memset(buffer, 0, BUFFER_SIZE);
	nbytes = read(gps_fd, buffer, BUFFER_SIZE);
	printf("%s", buffer);

    }
    tcsetattr(gps_fd,TCSANOW,&orig_tios);
    close(gps_fd);
    return 0;
}
